import path from 'path';
import dayjs from 'dayjs';
import { readdirSync, statSync } from 'fs';
const __dirname = path.resolve();

const getFileList = async (dir, type) => {
  const resArr = [];

  const findFile = async (nodeName) => {
    const dirPath = path.resolve(__dirname, `${dir}/${nodeName || ''}`);
    let files = readdirSync(dirPath);
    files.forEach((file) => {
      let filePath = `${dir}/${nodeName || ''}${file}`;
      if (file.endsWith(type)) {
        resArr.push(`${nodeName || ''}${file}`);
      } else if (statSync(filePath).isDirectory()) {
        findFile(`${file}/`);
      }
    });
  };
  findFile();

  return resArr;
};

const numberToLetters = (num) => {
  let letters = '';
  while (num > 0) {
    num--; // 转换为 0-based 索引
    letters = String.fromCharCode(65 + (num % 26)) + letters; // 65 是 'A' 的 ASCII 码
    num = Math.floor(num / 26);
  }
  return letters;
};

const getRange = (sheetId, rowCount, columnCount) => {
  const startColumn = 'A';
  const endColumn = numberToLetters(columnCount); // 将列数转换为字母
  const rangeStr = `${sheetId}!${startColumn}1:${endColumn}${rowCount}`;
  return rangeStr;
};

const getTime = (format) => {
  return dayjs().format(format || 'YYYY-MM-DD HH:mm:ss');
};

const delay = (ms) => {
  return new Promise((resolve) => setTimeout(resolve, ms));
};

export { getFileList, getRange, getTime, delay };
